package com.yuan.zsschool.ui;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.yuan.zsschool.R;

import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.http.app.DefaultParamsBuilder;
import org.xutils.http.app.RequestInterceptListener;
import org.xutils.http.request.UriRequest;
import org.xutils.x;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class MainActivitybak extends AppCompatActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	public void login(View view) {
		RequestParams params = new RequestParams("http://182.61.41.246/login");
		params.setMaxRetryCount(0);
		params.setReadTimeout(1000 * 30);
		params.setConnectTimeout(1000 * 30);
		params.setCancelFast(true);
		params.setCacheMaxAge(0);
		params.setCacheSize(0);
		params.setUseCookie(false);
		params.setAsJsonContent(true);
		try {
			params.setSslSocketFactory(new SSLSocketFactoryExtended());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}
		params.setBodyContent("{\"username\":\"admin\", \"password\":\"password\"}");
		params.setHostnameVerifier(new HostnameVerifier() {
			@Override
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		});
		x.http().post(params, new LoginCallback());
	}

	private static SSLSocketFactory trustAllSSlSocketFactory;

	public static SSLSocketFactory getTrustAllSSLSocketFactory() {
		if (trustAllSSlSocketFactory == null) {
			synchronized (DefaultParamsBuilder.class) {
				if (trustAllSSlSocketFactory == null) {
					// 信任所有证书
					TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
						@Override
						public X509Certificate[] getAcceptedIssuers() {
							return new X509Certificate[]{};
						}

						@Override
						public void checkClientTrusted(X509Certificate[] certs, String authType) {
						}

						@Override
						public void checkServerTrusted(X509Certificate[] certs, String authType) {
						}
					}};
					try {
						SSLContext sslContext = SSLContext.getInstance("TLS");
						sslContext.init(null, trustAllCerts, null);
						trustAllSSlSocketFactory = sslContext.getSocketFactory();
					} catch (Throwable ex) {
						LogUtil.e(ex.getMessage(), ex);
					}
				}
			}
		}

		return trustAllSSlSocketFactory;
	}

	private class LoginCallback implements Callback.CommonCallback<String>, RequestInterceptListener {
		@Override
		public void beforeRequest(UriRequest request) {

		}

		@Override
		public void afterRequest(UriRequest request) {
//			request.getResponseHeaders()
		}

		@Override
		public void onSuccess(String result) {

		}

		@Override
		public void onError(Throwable ex, boolean isOnCallback) {
			ex.printStackTrace();
		}

		@Override
		public void onCancelled(CancelledException cex) {

		}

		@Override
		public void onFinished() {

		}
	}

	public class SSLSocketFactoryExtended extends SSLSocketFactory {
		private SSLContext mSSLContext;
		private String[] mCiphers;
		private String[] mProtocols;


		public SSLSocketFactoryExtended() throws NoSuchAlgorithmException, KeyManagementException {
			initSSLSocketFactoryEx(null, null, null);
		}

		public String[] getDefaultCipherSuites() {
			return mCiphers;
		}

		public String[] getSupportedCipherSuites() {
			return mCiphers;
		}

		public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
			SSLSocketFactory factory = mSSLContext.getSocketFactory();
			SSLSocket ss = (SSLSocket) factory.createSocket(s, host, port, autoClose);

			ss.setEnabledProtocols(mProtocols);
			ss.setEnabledCipherSuites(mCiphers);
			return ss;
		}

		public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
			SSLSocketFactory factory = mSSLContext.getSocketFactory();
			SSLSocket ss = (SSLSocket) factory.createSocket(address, port, localAddress, localPort);

			ss.setEnabledProtocols(mProtocols);
			ss.setEnabledCipherSuites(mCiphers);

			return ss;
		}

		public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
			SSLSocketFactory factory = mSSLContext.getSocketFactory();
			SSLSocket ss = (SSLSocket) factory.createSocket(host, port, localHost, localPort);

			ss.setEnabledProtocols(mProtocols);
			ss.setEnabledCipherSuites(mCiphers);

			return ss;
		}

		public Socket createSocket(InetAddress host, int port) throws IOException {
			SSLSocketFactory factory = mSSLContext.getSocketFactory();
			SSLSocket ss = (SSLSocket) factory.createSocket(host, port);

			ss.setEnabledProtocols(mProtocols);
			ss.setEnabledCipherSuites(mCiphers);

			return ss;
		}

		public Socket createSocket(String host, int port) throws IOException {
			SSLSocketFactory factory = mSSLContext.getSocketFactory();
			SSLSocket ss = (SSLSocket) factory.createSocket(host, port);

			ss.setEnabledProtocols(mProtocols);
			ss.setEnabledCipherSuites(mCiphers);

			return ss;
		}

		private void initSSLSocketFactoryEx(KeyManager[] km, TrustManager[] tm, SecureRandom random)
				throws NoSuchAlgorithmException, KeyManagementException {
			mSSLContext = SSLContext.getInstance("TLS");
			mSSLContext.init(km, tm, random);

			mProtocols = GetProtocolList();
			mCiphers = GetCipherList();
		}

		protected String[] GetProtocolList() {
			String[] protocols = {"TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3"};
			String[] availableProtocols = null;

			SSLSocket socket = null;

			try {
				SSLSocketFactory factory = mSSLContext.getSocketFactory();
				socket = (SSLSocket) factory.createSocket();

				availableProtocols = socket.getSupportedProtocols();
			} catch (Exception e) {
				return new String[]{"TLSv1"};
			} finally {
				if (socket != null)
					try {
						socket.close();
					} catch (IOException e) {
					}
			}

			List<String> resultList = new ArrayList<String>();
			for (int i = 0; i < protocols.length; i++) {
				int idx = Arrays.binarySearch(availableProtocols, protocols[i]);
				if (idx >= 0)
					resultList.add(protocols[i]);
			}

			return resultList.toArray(new String[0]);
		}

		protected String[] GetCipherList() {
			List<String> cipherSuitesToEnable = new ArrayList<>();
			cipherSuitesToEnable.add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA");
			cipherSuitesToEnable.add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256");
			cipherSuitesToEnable.add("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256");
			cipherSuitesToEnable.add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA");
			cipherSuitesToEnable.add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256");
			cipherSuitesToEnable.add("TLS_DHE_RSA_WITH_AES_256_GCM_SHA384");
			List<String> resultList = new ArrayList<String>();
			SSLSocketFactory factory = mSSLContext.getSocketFactory();
			for (String s : factory.getSupportedCipherSuites()) {
				Log.e("CipherSuite type = ", s);
				resultList.add(s);
			}
			return resultList.toArray(new String[resultList.size()]);
//			return cipherSuitesToEnable.toArray(new String[cipherSuitesToEnable.size()]);

		}

	}
}
